package com.jiudengnile.liushu.web.action;

import java.net.MalformedURLException;
import java.net.URL;

import wint.help.biz.result.Result;
import wint.help.mvc.WebConstants;
import wint.help.mvc.security.csrf.CsrfTokenUtil;
import wint.lang.utils.StringUtil;
import wint.mvc.flow.FlowData;
import wint.mvc.form.Form;
import wint.mvc.module.annotations.Action;
import wint.mvc.template.Context;

import com.jiudengnile.liushu.biz.ao.UserAO;
import com.jiudengnile.liushu.biz.domains.BaseUserDO;
import com.jiudengnile.liushu.biz.resultcodes.UserResultCodes;
import com.jiudengnile.liushu.web.common.base.BaseAction;

public class User extends BaseAction {

	private UserAO userAO;
	
	@Action(defaultTarget="/user/register")
	public void doRegister(FlowData flowData, Context context) {
		Form form = flowData.getForm("user.register");
		BaseUserDO baseUserDO = new BaseUserDO();
		if (!form.apply(baseUserDO)) {
			return;
		}
		Result result = userAO.registerByNick(baseUserDO);
		if (result.isSuccess()) {
			handleRedirect(flowData, "user/registerSuccess");
		} else {
			this.handleError(result, flowData, context);
		}
	}
	
	private void handleRedirect(FlowData flowData, String defaultTarget) {
		String url = flowData.getParameters().getString(WebConstants.REDIRECT_PARAM_NAME);
		if (!canRedirect(url)) {
			flowData.redirectTo("baseModule", defaultTarget);
		} else {
			flowData.redirectTo(url);
		}
	}
	
	public void doLogout(FlowData flowData, Context context) {
		if (!CsrfTokenUtil.checkCsrfByParameter(flowData, "token")) {
			flowData.setTarget("error");
			sendToError(flowData, context, UserResultCodes.LOGOUT_FAIL_BY_CSRF_TOKEN);
			return;
		}
		Result result = userAO.handleLogout();
		if (result.isSuccess()) {
			handleRedirect(flowData, "user/login");
		} else {
			this.handleResult(result, flowData, context);
		}
	}
	
	@Action(defaultTarget="/user/login")
	public void doLogin(FlowData flowData, Context context) {
		Form form = flowData.getForm("user.login");
		BaseUserDO baseUserDO = new BaseUserDO();
		if (!form.apply(baseUserDO)) {
			return;
		}
		Result result = userAO.handleLogin(baseUserDO);
		if (result.isSuccess()) {
			handleRedirect(flowData, "/");
		} else {
			this.handleError(result, flowData, context);
		}
		
	}
	
	private boolean canRedirect(String url) {
		// 是否可以跳转到相应页面
		// 如果原来就是登陆页面，则返回false，也就是跳转到首页
		if (StringUtil.isEmpty(url)) {
			return false;
		}
		try {
			URL urlObject = new URL(url);
			String path = urlObject.getPath();
			String target = StringUtil.getLastAfter(path, "/");
			String targetName = StringUtil.getLastBefore(target, ".");
			if ("user/login".equalsIgnoreCase(targetName)) {
				return false;
			}
			
			// TODO 判断跳转到站外域名
			
			return true;
		} catch (MalformedURLException e) {
			return false;
		}
	}

	public void setUserAO(UserAO userAO) {
		this.userAO = userAO;
	}
	
}
